package com.jfinal.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.jfinal.util.PdfUtil;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;
import com.jfinal.upload.UploadFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * PDF工具
 */
@Path(value = "/", viewPath = "/pdf")
public class PdfController extends Controller {

    public void index() {
        render("index.html");
    }

    public void uploader() {
        UploadFile uploadFile = null;
        String msg = "上传成功";
        try {
            // 按日期分文件夹存储附件
            uploadFile = getFile("file", DateUtil.today(), 50 * 1024 * 1024);
            // 得到源文件的后缀
            if (uploadFile != null && uploadFile.getFile() != null && uploadFile.getFile().exists()) {
                File file = uploadFile.getFile();
                String ext = FileUtil.extName(file);
                String newPath = uploadFile.getUploadPath() + File.separator + IdUtil.fastSimpleUUID()
                        + "." + FileUtil.extName(file);
                FileUtil.move(file, new File(newPath), true);

                String pdfPath = newPath.replace("." + FileUtil.extName(file), ".pdf");
                List<Kv> nameArray = new ArrayList<>();
                // 文件换成PDF和图片
                if (PdfUtil.officeToPdf(newPath, uploadFile.getUploadPath())) {
                    List<String> pathArray = PdfUtil.pdfToImage(pdfPath,
                            uploadFile.getUploadPath() + File.separator + FileUtil.mainName(newPath),
                            96);

                    for (String url : pathArray) {
                        nameArray.add(
                                Kv.by("url", url.replace(PathKit.getWebRootPath(), "").replace("\\", "/"))
                                        .set("name", FileUtil.mainName(file)));
                    }
                }

                renderJson(Ret.ok(msg)
                        .set("name", FileUtil.mainName(file))
                        .set("url", pdfPath.replace(PathKit.getWebRootPath(), "").replace("\\", "/"))
                        .set("urls", nameArray)
                        .set("type", ext)
                        .set("t", StrUtil.subPre(ext, 1).toUpperCase()));
                return;
            }
        } catch (Exception e) {
            msg = e.getMessage().toString();
            if (msg.indexOf("content length of") > 0) {
                msg = "文件超过指定大小，请重新上传";
            }
            renderJson(Ret.fail("上传失败，详情：" + msg));
            return;
        }

        renderJson(Ret.fail("上传失败"));
    }
}
